<template>
  <a-modal
    title="添加设备"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="model && model.id > 0" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="名称">
          <a-input v-decorator="['alarmsName']" />
        </a-form-item>
        <a-form-item label="设备编码">
          <a-input v-decorator="['equipmentNo']" />
        </a-form-item>
        <a-form-item label="初始密码">
          <a-input v-decorator="['password']" />
        </a-form-item>
        <a-form-item label="设备分组">
          <a-select v-decorator="['alarmsGroup']" allowClear>
            <a-select-option v-for="item in groupList " :key="item.Id" :value='item.name'>{{ item.name }}</a-select-option>
            <!-- <a-select-option value="jack">Jack</a-select-option>
            <a-select-option value="lucy">Lucy</a-select-option>
            <a-select-option value="tom">Tom</a-select-option> -->
          </a-select>
        </a-form-item>
        <a-form-item label="设备地址">
          <a-input v-decorator="['address']" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { getDeviceGroupList } from '@/api/device'

// 表单字段
const fields = ['id', 'alarmsName', 'equipmentNo', 'password', 'alarmsGroup', 'address']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      form: this.$form.createForm(this),
      groupList: []
    }
  },
  created () {
    this.getGroupList()
    console.log('custom modal created')

    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  methods: {
    getGroupList () {
      var params = {
        pageNum: 1,
        pageSize: 100
      }
      getDeviceGroupList(params).then(res => {
        this.groupList = res.data.list
        console.log('groupList', this.groupList)
      })
    }
  }
}
</script>
